<template>
  <div class="video-generate-container">
    <!-- 左侧参数调整区域 -->
    <div class="left-panel">
      <div class="panel-header">
        <h2>虚拟人视频生成</h2>
      </div>
      
      <div class="form-container">
        <!-- 虚拟人选择 -->
        <div class="form-group">
          <label>虚拟人模型:</label>
          <el-select v-model="formData.virtualmanKey" placeholder="请选择虚拟人模型">
            <el-option label="默认虚拟人" value="487ebcd75d1243bdbc03cdbe0fb694b2"></el-option>
            <el-option label="商务虚拟人" value="business"></el-option>
            <el-option label="卡通虚拟人" value="cartoon"></el-option>
          </el-select>
        </div>

        <!-- 语速调整 -->
        <div class="form-group">
          <label>语速: {{ formData.speed }}x</label>
          <el-slider 
            v-model="formData.speed" 
            :min="0.5" 
            :max="2.0" 
            :step="0.1"
            show-stops
          ></el-slider>
        </div>

        <!-- 文本输入方式选择 -->
        <div class="form-group">
          <label>输入方式:</label>
          <el-radio-group v-model="inputType">
            <el-radio label="text">文本输入</el-radio>
            <el-radio label="file">文件上传</el-radio>
          </el-radio-group>
        </div>

        <!-- 文本输入区域 -->
        <div class="form-group" v-if="inputType === 'text'">
          <label>文本内容:</label>
          <el-input
            v-model="formData.ssmlText"
            type="textarea"
            :rows="6"
            placeholder="请输入要生成视频的文本内容（至少4个字符）..."
          ></el-input>
        </div>

        <!-- 文件上传区域 -->
        <div class="form-group" v-if="inputType === 'file'">
          <label>上传文件:</label>
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".txt"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 txt 格式文件 
              </div>
            </template>
          </el-upload>
        </div>

        <!-- 生成按钮 -->
        <div class="form-group">
          <el-button 
            type="primary" 
            size="large" 
            :loading="isGenerating"
            @click="generateVideo"
            :disabled="!canGenerate"
          >
            {{ isGenerating ? '生成中...' : '生成视频' }}
          </el-button>
        </div>

        <!-- 任务状态 -->
        <div class="form-group" style="margin-top: 30px;">
          <label>任务ID:</label>
          <el-input v-model="taskId" placeholder="请输入任务ID"></el-input>
          <el-button type="success" size="small" @click="() => queryProgress(true)" :disabled="isQuerying" class="query-progress-btn" style="margin-top: 10px;">
            <el-icon v-if="isQuerying" class="is-loading"><Loading /></el-icon>
            {{ isQuerying ? '查询中...' : '查询进度' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 右侧视频播放区域 -->
    <div class="right-panel">
      <div class="panel-header">
        <h2>视频预览</h2>
      </div>
      
      <div class="video-container">
        <div v-if="!videoUrl" class="video-placeholder">
          <el-icon size="64"><VideoPlay /></el-icon>
          <p>暂无视频</p>
        </div>
        
        <div v-else class="video-wrapper">
          <video 
            ref="videoPlayer"
            controls
            preload="metadata"
            class="video-player"
            :class="{ 'fullscreen-video': isFullscreen }"
          >
            <source :src="videoUrl" type="video/webm">
            <source :src="videoUrl" type="video/mp4">
            您的浏览器不支持视频播放
          </video>
        </div>
      </div>

      <!-- 视频控制按钮 -->
      <div class="video-controls" v-if="videoUrl">
        <el-button @click="playVideo">播放</el-button>
        <el-button @click="pauseVideo">暂停</el-button>
        <el-button @click="toggleFullscreen">
          {{ isFullscreen ? '退出全屏' : '全屏播放' }}
        </el-button>
        <el-button @click="downloadVideo">下载</el-button>
      </div>

      <!-- 保存按钮 -->
      <div class="save-controls" v-if="videoUrl">
        <el-button 
          type="success" 
          size="large"
          :loading="isSaving"
          @click="saveMedia"
        >
          {{ isSaving ? '保存中...' : '保存到我的作品' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay, FullScreen, Aim, Loading } from '@element-plus/icons-vue'
import { createVideoApi, getVideoUrlApi, saveMediaApi } from '../apis/videoAPI.js'
import router from '../router/index.js'

// 响应式数据
const formData = ref({
  virtualmanKey: '487ebcd75d1243bdbc03cdbe0fb694b2',
  ssmlText: '',
  speed: 1.0
})

const inputType = ref('text')
const uploadedFile = ref(null)
const isGenerating = ref(false)
const isQuerying = ref(false)
const isFullscreen = ref(false)
const taskId = ref('')
const videoUrl = ref('')
const videoPlayer = ref(null)
const uploadRef = ref(null)
const lastQueryTime = ref(0)
const isManualQuery = ref(false)
const isSaving = ref(false)

// 计算属性
const canGenerate = computed(() => {
  if (inputType.value === 'text') {
    return formData.value.ssmlText.trim().length >= 4
  } else {
    return uploadedFile.value !== null
  }
})

// 文件处理方法
const handleFileChange = (file) => {
  uploadedFile.value = file.raw
}

const handleFileRemove = () => {
  uploadedFile.value = null
}

// 生成视频
const generateVideo = async () => {
  try {
    isGenerating.value = true
    
    const formDataToSend = new FormData()
    formDataToSend.append('virtualmanKey', formData.value.virtualmanKey)
    formDataToSend.append('speed', formData.value.speed)
    
    if (inputType.value === 'text') {
      formDataToSend.append('ssmlText', formData.value.ssmlText)
    } else if (uploadedFile.value) {
      formDataToSend.append('file', uploadedFile.value)
    }
    
    const response = await createVideoApi(formDataToSend)
    
    // 根据后端Result格式处理响应
    if (response.code === 200) {
      taskId.value = response.data
      ElMessage.success(response.msg + '，任务ID: ' + response.data)
      // 可以开始轮询检查状态
      startStatusCheck()
    } else {
      ElMessage.error(response.msg || '生成失败')
      if (response.description) {
        console.error('错误详情:', response.description)
      }
    }
  } catch (error) {
    console.error('生成视频失败:', error)
    ElMessage.error('生成视频失败，请稍后重试')
  } finally {
    isGenerating.value = false
  }
}

// 查询进度
const queryProgress = async (manual = false) => {
  if (!taskId.value) {
    if (manual) {
      ElMessage.warning('请输入任务ID')
    }
    return
  }
  
  // 检查3秒限制（仅对手动查询）
  if (manual) {
    const now = Date.now()
    if (now - lastQueryTime.value < 3000) {
      ElMessage.warning('请等待3秒后再次查询')
      return
    }
    lastQueryTime.value = now
  }
  
  try {
    isQuerying.value = true
    isManualQuery.value = manual
    
    const response = await getVideoUrlApi(taskId.value)
    
    // 根据新的后端接口处理响应
    if (response.code === 200) {
      const data = response.data
      
      // 检查返回的数据类型
      if (typeof data === 'string' && (data.startsWith('http') || data.includes('video'))) {
        // Success: 获取到视频URL
        videoUrl.value = data
        if (manual) {
          ElMessage.success(response.msg || '视频生成成功')
        }
      } else {
        // Making: 视频生成中
        if (manual) {
          ElMessage.info(response.msg || '视频生成中，请3秒后重试')
        }
      }
    } else {
      // Error: 生成失败
      if (manual) {
        ElMessage.error(response.msg || '视频生成失败')
      }
      console.error('视频生成失败:', response.msg)
    }
  } catch (error) {
    console.error('查询进度失败:', error)
    if (manual) {
      ElMessage.error('查询进度失败，请稍后重试')
    }
  } finally {
    isQuerying.value = false
    isManualQuery.value = false
  }
}

// 开始状态检查轮询
const startStatusCheck = () => {
  const interval = setInterval(async () => {
    await queryProgress(false) // 轮播查询，不显示提示消息
    if (videoUrl.value) {
      clearInterval(interval)
    }
  }, 5000) // 每5秒检查一次
  
  // 30秒后停止轮询
  setTimeout(() => {
    clearInterval(interval)
  }, 30000)
}

// 视频控制方法
const playVideo = () => {
  if (videoPlayer.value) {
    videoPlayer.value.play()
  }
}

const pauseVideo = () => {
  if (videoPlayer.value) {
    videoPlayer.value.pause()
  }
}

const downloadVideo = () => {
  if (videoUrl.value) {
    const link = document.createElement('a')
    link.href = videoUrl.value
    link.download = 'generated-video.webm'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

// 全屏切换
const toggleFullscreen = () => {
  if (!videoPlayer.value) return
  
  if (!isFullscreen.value) {
    // 进入全屏
    if (videoPlayer.value.requestFullscreen) {
      videoPlayer.value.requestFullscreen()
    } else if (videoPlayer.value.webkitRequestFullscreen) {
      videoPlayer.value.webkitRequestFullscreen()
    } else if (videoPlayer.value.mozRequestFullScreen) {
      videoPlayer.value.mozRequestFullScreen()
    } else if (videoPlayer.value.msRequestFullscreen) {
      videoPlayer.value.msRequestFullscreen()
    }
    isFullscreen.value = true
  } else {
    // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    }
    isFullscreen.value = false
  }
}

// 保存媒体
const saveMedia = async () => {
  if (!taskId.value || !videoUrl.value) {
    ElMessage.warning('缺少任务ID或视频URL')
    return
  }
  
  try {
    isSaving.value = true
    
    const response = await saveMediaApi(taskId.value, videoUrl.value)
    
    if (response.code === 200) {
      ElMessage.success(response.msg || '保存成功')
    } else {
      // 检查是否为用户未登录
      if (response.code === 400 && response.msg && response.msg.includes('用户未登录')) {
        ElMessage.warning('用户未登录，请重新登录')
        // 跳转到登录页面
        router.push('/login')
        return
      }
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存媒体失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    isSaving.value = false
  }
}

onMounted(() => {
  // 监听全屏状态变化
  const handleFullscreenChange = () => {
    const isCurrentlyFullscreen = !!(document.fullscreenElement || 
                                    document.webkitFullscreenElement || 
                                    document.mozFullScreenElement || 
                                    document.msFullscreenElement)
    isFullscreen.value = isCurrentlyFullscreen
  }
  
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('mozfullscreenchange', handleFullscreenChange)
  document.addEventListener('MSFullscreenChange', handleFullscreenChange)
})
</script>

<style scoped>
.video-generate-container {
  display: flex;
  min-height: calc(100vh - 105px); /* 减去导航栏和底部版权的高度 */
  margin-bottom: 60px; /* 为底部版权信息留出空间 */
  background: linear-gradient(to bottom, #50a8fe, #f0f2f5);
  border-radius: 12px;
  margin: 10px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.left-panel {
  width: 420px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  overflow-y: auto;
  box-shadow: 2px 0 20px rgba(0, 0, 0, 0.1);
}

.right-panel {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 25px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  background: linear-gradient(to bottom, rgba(80, 168, 254, 0.1), rgba(240, 242, 245, 0.1));
  position: relative;
}

.panel-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(to right, #50a8fe, #3b82f6);
}

.panel-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-container {
  padding: 25px;
}

.form-group {
  margin-bottom: 25px;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 10px;
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.video-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px;
  background: linear-gradient(to bottom, rgba(80, 168, 254, 0.05), rgba(240, 242, 245, 0.05));
}

.video-placeholder {
  text-align: center;
  color: #7f8c8d;
  padding: 40px;
  border: 2px dashed #bdc3c7;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

.video-placeholder:hover {
  border-color: #50a8fe;
  background: rgba(255, 255, 255, 0.9);
}

.video-placeholder p {
  margin-top: 15px;
  font-size: 16px;
  font-weight: 500;
}

.video-wrapper {
  position: relative;
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
}

.video-player {
  width: 100%;
  height: auto;
  border-radius: 12px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
  background: #000;
  transition: transform 0.3s ease;
}

.video-player:hover {
  transform: translateY(-2px);
}

.fullscreen-video {
  width: 100vw;
  height: 100vh;
  border-radius: 0;
  object-fit: contain;
  transform: none;
}

.fullscreen-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 10;
  backdrop-filter: blur(5px);
}

.fullscreen-btn:hover {
  background: rgba(0, 0, 0, 0.9);
  transform: scale(1.05);
}

.video-controls {
  padding: 25px;
  text-align: center;
  border-top: 1px solid rgba(255, 255, 255, 0.3);
  background: linear-gradient(to bottom, rgba(80, 168, 254, 0.05), rgba(240, 242, 245, 0.05));
}

.video-controls .el-button {
  margin: 0 8px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.video-controls .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.save-controls {
  padding: 30px;
  text-align: center;
  border-top: 1px solid rgba(255, 255, 255, 0.3);
  background: linear-gradient(to bottom, rgba(80, 168, 254, 0.1), rgba(240, 242, 245, 0.1));
  margin-bottom: 20px; /* 确保与底部版权信息有足够间距 */
}

.save-controls .el-button {
  width: 220px;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 25px;
  background: linear-gradient(to bottom, #50a8fe, #3b82f6);
  border: none;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(80, 168, 254, 0.4);
}

.save-controls .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(80, 168, 254, 0.6);
}

.save-controls .el-button:active {
  transform: translateY(0);
}

.el-select,
.el-input,
.el-slider {
  width: 100%;
}

.el-select .el-input__inner,
.el-input__inner,
.el-textarea__inner {
  border-radius: 8px;
  border: 2px solid #e9ecef;
  transition: all 0.3s ease;
}

.el-select .el-input__inner:focus,
.el-input__inner:focus,
.el-textarea__inner:focus {
  border-color: #50a8fe;
  box-shadow: 0 0 0 3px rgba(80, 168, 254, 0.1);
}

.el-textarea {
  width: 100%;
}

.el-textarea .el-textarea__inner {
  border-radius: 8px;
  resize: vertical;
  min-height: 120px;
}

.el-upload {
  width: 100%;
}

.el-upload .el-button {
  border-radius: 8px;
  font-weight: 500;
}

.el-button--large {
  width: 100%;
  height: 55px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: linear-gradient(to bottom, #50a8fe, #3b82f6);
  border: none;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(80, 168, 254, 0.4);
}

.el-button--large:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(80, 168, 254, 0.6);
}

.el-slider__runway {
  background-color: #e9ecef;
  border-radius: 10px;
}

.el-slider__bar {
  background: linear-gradient(to bottom, #50a8fe, #3b82f6);
  border-radius: 10px;
}

.el-slider__button {
  border: 3px solid #50a8fe;
  background: white;
  box-shadow: 0 2px 8px rgba(80, 168, 254, 0.3);
}

.el-radio-group .el-radio {
  margin-right: 20px;
}

.el-radio__input.is-checked .el-radio__inner {
  background-color: #50a8fe;
  border-color: #50a8fe;
}

.query-progress-btn {
  width: 100%;
  height: 40px;
  font-weight: 600;
  border-radius: 8px;
  background: linear-gradient(to right, #67c23a, #85ce61);
  border: none;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 3px 12px rgba(103, 194, 58, 0.3);
}

.query-progress-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 5px 18px rgba(103, 194, 58, 0.5);
  background: linear-gradient(to right, #85ce61, #67c23a);
}

.query-progress-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.query-progress-btn .el-icon {
  margin-right: 6px;
}

@media (max-width: 768px) {
    .video-generate-container {
      flex-direction: column;
      margin: 5px;
      min-height: calc(100vh - 100px);
      margin-bottom: 55px;
    }
    
    .left-panel {
      width: 100%;
    }
    
    .right-panel {
      min-height: 400px;
    }
    
    .save-controls {
      margin-bottom: 20px;
    }
  }
</style>